<?php

namespace app\model;

use think\db\Query;
use think\Model;

class Reservation extends Model
{
  protected $table = 'reservation';

  protected $schema = [
    'date',
    'period',
    'deadline',
    'createtime',
    'status'
  ];

  public function packages()
  {
    return $this->hasMany(Package::class, 'reservation_id');
  }

  // 创建新的订餐记录
  public static function createReservation(array $data)
  {
    $row = self::create($data);
    $row->save();
    return $row;
  }

  // 更新订餐记录
  public static function updateReservation(int $id, array $data)
  {
    $reservation = self::find($id);
    if ($reservation) {
      return $reservation->update($data);
    }
    return false;
  }

  // 删除订餐记录
  public static function deleteReservation(int $id)
  {
    $reservation = self::find($id);
    if ($reservation) {
      return $reservation->delete();
    }
    return false;
  }

  // 根据ID获取订餐记录
  public static function getReservationById(int $id)
  {
    return self::find($id);
  }

  // 获取分页订餐记录
  public static function getReservations(int $page, int $pagesize, array $filters = [])
  {
    $reservations = self::with([
      'packages.dishes'
    ])->page($page, $pagesize)->where($filters)->order("date desc, period asc")->select();
    $total = self::where($filters)->count();
    $data = [
      "lists" => $reservations,
      "total" => $total,
      "page" => (int) $page,
      "limit" => (int) $pagesize,
    ];
    return $data;
  }
}
